package com.wenwu.controller.competence;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.wenwu.common.bean.Function;
import com.wenwu.common.bean.Resource;
import com.wenwu.common.bean.Role;
import com.wenwu.common.bean.User;
import com.wenwu.common.page.PageUtils;
import com.wenwu.common.page.PaginationVO;
import com.wenwu.common.tag.SysConstants;
import com.wenwu.common.utils.JsonUtils;
import com.wenwu.service.FunctionService;
import com.wenwu.service.ResourceService;

/**
 * @project ATHome-Manager
 * @class ResourceController.java
 * @author zhujiagui E-mail:<zhujiagui@zkingsoft.com>
 * @date 2015年3月4日 上午11:17:58
 * @description 资源管理模块
 */
@Controller(value = "ResourceController")
@RequestMapping(value = "/resource")
public class ResourceController {
	@Autowired
	private ResourceService resourceService;
	@Autowired
	private FunctionService functionService;
	Logger log = Logger.getLogger(this.getClass());
	// 用来创建json数据
	private JsonGenerator jsonGenerator = null;
	// 进入页面
	@RequestMapping(value = "/mgr/init")
	public String initPage() {
		log.info("进入资源管理模块页面...");
		return "resource/resourcelist";
	}

	@RequestMapping(value = "/mgr/resourceform")
	public String functionform() {
		return "resource/resourceform";
	}

	// 列表显示
	@RequestMapping(value = "/mgr/showList")
	public void showList(Model model, HttpServletRequest request,
			HttpServletResponse response, Role role) throws Exception {
		log.info("查询资源列表...");
		PaginationVO pageVo = PageUtils.getPaginationInfo(request);
		try {
			List<Resource> list = resourceService.selectAllList();// 查询所有数据
			pageVo.setList(list);// 将数据设置到PaginationVO对象中
			jsonGenerator = JsonUtils.getJsonGenerator(response);
			jsonGenerator.writeObject(pageVo);// 将PaginationVO对象以json格式写回页面
		} catch (Exception e) {// 异常处理
			log.info(e.getMessage());
			model.addAttribute("errorMsg", "系统异常，请稍后重试!");
		}
	}

	/**
	 * 增加
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/mgr/addResource", method = { RequestMethod.POST })
	public void addResource(Resource resource, HttpServletResponse response)
			throws Exception {
		jsonGenerator = JsonUtils.getJsonGenerator(response);
		try {
			if (resource.getSourceId() == null) {
				resourceService.addResource(resource);
				jsonGenerator.writeObject("添加成功");
			} else {
				resourceService.updateResource(resource);
				jsonGenerator.writeObject("修改成功");
			}
		} catch (Exception e) {
			jsonGenerator.writeObject("保存失败," + e.getMessage());
		}
	}

	/**
	 * 查询修改信息
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/mgr/showUpdate")
	public void showUpdate(HttpServletResponse response,
			@RequestParam(required = false, value = "sourceId") Integer sourceId)
			throws Exception {
		if (sourceId != null) {
			Resource resource = resourceService.selectByKey(sourceId);
			jsonGenerator = JsonUtils.getJsonGenerator(response);
			jsonGenerator.writeObject(resource);
		}
	}

	/**
	 * 批量删除
	 * 
	 * @param response
	 * @param userId
	 * @throws Exception
	 */
	@RequestMapping(value = "/mgr/deleteResource")
	public void deleteResource(HttpServletResponse response,
			@RequestParam(required = false, value = "key") String key)
			throws Exception {
		log.info("主键：" + key);
		if (key != null) {
			List<String> keys = new ArrayList<String>();
			String[] objs = key.split(",");
			for (String k : objs) {
				keys.add(k);
			}
			jsonGenerator = JsonUtils.getJsonGenerator(response);
			try {
				int result = resourceService.deleteResourceByKey(keys);
				jsonGenerator.writeObject("成功删除" + result + "条数据");
			} catch (Exception e) {
				jsonGenerator.writeObject("删除数据失败");
			}
		}
	}

	/**
	 * 加载所有窗体资源
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/mgr/loadResource")
	public void loadResource(HttpServletResponse response) throws Exception {
		// 加载所有为窗体的数据
		try {
			List<Resource> list = resourceService.selectAllList();
			List<Function> flist = functionService.selectList();
			Map<Integer, Function> functionmap = new HashMap<Integer, Function>();
			for (Function function : flist) {
				functionmap.put(function.getFunctionId(), function);
			}
			List<Function> functionlist = null;
			List<Resource> resourceList = new ArrayList<Resource>();
			for (Resource resource : list) {
				functionlist = new ArrayList<Function>();
				if (resource.getParentId() != null
						&& resource.getParentId() > 0
						&& !StringUtils.isEmpty(resource.getFunctionIds())) {// 子资源
					String[] fids = resource.getFunctionIds().split(",");
					for (String fid : fids) {
						functionlist
								.add(functionmap.get(Integer.parseInt(fid)));
					}
					resource.setFunctions(functionlist);
				}
				resourceList.add(resource);
			}
			PaginationVO pageVo = new PaginationVO();
			pageVo.setList(resourceList);
			jsonGenerator = JsonUtils.getJsonGenerator(response);
			jsonGenerator.writeObject(pageVo);
		} catch (Exception e) {
			log.info("系统异常，" + e.getMessage());
		}
	}

	/**
	 * 根据用户角色,动态加载菜单
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/mgr/showResourceMenu")
	public void showResourceMenu(HttpSession session,
			HttpServletResponse response) throws Exception {
		// 获取登录用户
		try {
			User user = (User) session.getAttribute(SysConstants.LOGIN_KEY);
			jsonGenerator = JsonUtils.getJsonGenerator(response);
			if (user != null) {
				List<String> ids =null;
				if (!user.getUserName().equals(SysConstants.SUPERMAN)&& !StringUtils.isEmpty(user.getRoleId())) {// 超级用户查询所有
					ids= new ArrayList<String>();
					String[] objs = user.getRoleId().split(",");
					for (String k : objs) {
						ids.add(k);
					}
				}
				List<Resource> list = resourceService
						.selectResourceByRoleid(ids);
				PaginationVO pageVo = new PaginationVO();
				pageVo.setList(list);
				jsonGenerator.writeObject(pageVo);
			} else {
				jsonGenerator.writeObject("登陆超时或用户未分配角色！");
			}
		} catch (Exception e) {
			throw new Exception("系统异常",e);
		}
	}
}
